package pl.edu.agh.gronoMining.owlChecker;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class CheckTags {

	private List<String> tagsList;
	
	private int lineNo = 0;
	
	public void checkTags(File f) throws IOException {
		FileReader reader = new FileReader(f);
		int c = 0;
		
		tagsList = new LinkedList<String>();
		
		lineNo = 0;
		
		int state = 0;
		String tagName = "";
		while (c != -1) {
			c = reader.read();
			//System.out.print(c);
			
			if (c == '\n') {
				lineNo++;
			}
			
			switch (state) {
			
			case 0:
				if (c == '<') {
					state = 1;
					tagName = "";
				}
				break;
			case 1:
				if (c == '/') {
					state = 2;
				} else if (c == ' ') {
					state = 3;
				} else if (c == '>') {
					setOpenTag(tagName);
					state = 0;
				} else {
					tagName += (char) c;
				}
				break;
			case 2:
				if (c == '>') {
					state = 0;
					setOpenCloseTag(tagName);
				} else {
					tagName += (char) c;
					state = 4;
				}
				break;
			case 3:
				if (c == '>') {
					setOpenTag(tagName);
					state = 0;
				} else if (c == '/') {
					state = 5;
				}
				break;
			case 4:
				if (c == '>') {
					state = 0;
					setCloseTag(tagName);
				} else {
					tagName += (char) c;
				}
				break;
			case 5:
				if (c == '>') {
					setOpenCloseTag(tagName);
					state = 0;
				} else {
					state = 3;
				}
				break;
			}
		}
		//System.out.println("end state: "+state);
		if (state != 0)
			throw new IOException("State should be 0 (was "+state+")");
		//System.out.println(tagsList.size());
		if (tagsList.size() != 0) {
			throw new IOException("No close tag for "+tagsList.get(tagsList.size() - 1));
		}
	}
	
	public void setOpenTag(String tagName) {
		tagName = tagName.trim();
		if (tagName.equals("?xml"))
			return;
		System.out.println("open "+lineNo +": "+tagName);
		tagsList.add(tagName);
	}
	
	public void setCloseTag(String tagName) throws IOException {
		tagName = tagName.trim();
		System.out.println("close "+ lineNo +": "+tagName);
		String s = tagsList.get(tagsList.size()-1);
		if (! s.equals(tagName)) {
			throw new IOException("Wrong tag - should be '"+s+"' was '"+tagName+"'");
		}
		tagsList.remove(tagsList.size()-1);
	}
	
	public void setOpenCloseTag(String tagName) {
		tagName = tagName.trim();
		System.out.println("open-close "+lineNo +": "+tagName);
	}
	
	public static void main(String[] args) {
		File f = new File("data/owl/7/smallUserForumOntology.owl");
		CheckTags checker = new CheckTags();
		try {
			checker.checkTags(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
